<template>
  <div class="roles">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="showAddModal = true">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索角色名称、描述..."
          style="width: 300px; margin-right: 16px;"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="statusFilter" placeholder="全部状态" style="width: 120px;" clearable @clear="statusFilter = null">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </div>

      <el-table :data="filteredRoles" style="width: 100%" v-loading="loading">
        <el-table-column label="角色信息" min-width="200">
          <template #default="{ row }">
            <div>
              <div style="font-weight: 500;">{{ row.roleName }}</div>
              <div style="font-size: 12px; color: #999;">{{ row.roleDes }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="150">
          <template #default="{ row }">
            <el-text type="info">{{ formatDate(row.createTime) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="assignPermissions(row)">分配权限</el-button>
            <el-button type="warning" size="small" @click="editRole(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteRole(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog v-model="isModalVisible" :title="showAddModal ? '新增角色' : '编辑角色'" width="600px">
      <el-form :model="roleForm" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="如：宿管员" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDes">
          <el-input 
            v-model="roleForm.roleDes" 
            type="textarea" 
            placeholder="角色的详细描述..."
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeModal">取消</el-button>
          <el-button type="primary" @click="saveRole">
            {{ showAddModal ? '新增' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog v-model="showPermissionDialog" title="分配权限" width="600px">
      <el-tree
        :data="permissionTree"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedPermissionIds"
        ref="permissionTreeRef"
        :props="treeProps"
        :check-strictly="false"
        class="permission-tree"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermissionDialog = false">取消</el-button>
          <el-button type="primary" @click="savePermissionAssignment">保存权限</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance,nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { 
  querySysRoleAPI, 
  addSysRoleAPI, 
  updateSysRoleAPI, 
  deleteSysRoleAPI,
  queryRolePermissionsAPI,  // 新增：查询角色已有权限
} from '@/apis/sysAPI'
import { sysPermissionQueryAPI, assignPermissionsAPI } from '@/apis/sysAPI'

// 响应式数据
const searchQuery = ref('')
const statusFilter = ref(null)
const showAddModal = ref(false)
const showEditModal = ref(false)
const editingRole = ref(null)

// 权限分配相关数据
const showPermissionDialog = ref(false)
const currentRole = ref(null)
const allPermissions = ref([])
const permissionTree = ref([])
const checkedPermissionIds = ref([])
const permissionTreeRef = ref(null)

// 树形结构配置
const treeProps = {
  label: 'permissionName',
  children: 'children'
}

// 角色表单
const roleForm = ref({
  roleName: '',
  roleDes: '',
  status: 1
})

// 角色数据
const roles = ref([])
const loading = ref(false)

// 计算属性
const filteredRoles = computed(() => {
  let filtered = roles.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(role => 
      role.roleName.toLowerCase().includes(query) ||
      role.roleDes.toLowerCase().includes(query)
    )
  }

  // 状态过滤
  if (statusFilter.value !== null) {
    filtered = filtered.filter(role => role.status === statusFilter.value)
  }

  return filtered
})

const isModalVisible = computed({
  get: () => showAddModal.value || showEditModal.value,
  set: (value) => {
    if (!value) {
      showAddModal.value = false
      showEditModal.value = false
    }
  }
})


// 方法

const getStatusText = (status) => {
  const statusMap = {
    1: '启用',
    0: '禁用'
  }
  return statusMap[status] || status
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 加载角色数据
const loadRoles = async () => {
  try {
    loading.value = true
    const response = await querySysRoleAPI()
    if (response.code === 0) {
      roles.value = response.data
    } else {
      ElMessage.error('加载角色数据失败')
    }
  } catch (error) {
    console.error('加载角色数据失败:', error)
    ElMessage.error('加载角色数据失败')
  } finally {
    loading.value = false
  }
}

// 加载所有权限并构建树形结构
const loadAllPermissions = async () => {
  try {
    const response = await sysPermissionQueryAPI()
    if (response.data && response.code === 0) {
      allPermissions.value = response.data
      permissionTree.value = buildPermissionTree(response.data)
    } else {
      ElMessage.error('获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  }
}

// 构建权限树形结构
const buildPermissionTree = (permissions) => {
  const map = {}
  const tree = []
  
  // 先将所有权限放入map
  permissions.forEach(permission => {
    map[permission.id] = { ...permission, children: [] }
  })
  
  // 构建树形结构
  permissions.forEach(permission => {
    if (permission.parentId) {
      if (map[permission.parentId]) {
        map[permission.parentId].children.push(map[permission.id])
      } else {
        tree.push(map[permission.id])
      }
    } else {
      tree.push(map[permission.id])
    }
  })
  
  return tree
}

// 获取角色已分配的权限
const getRolePermissions = async (roleId) => {
  try {
    const response = await queryRolePermissionsAPI(roleId)
    if (response.data && response.code === 0) {
      return response.data.map(p => p.id)
    }
    return []
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
    return []
  }
}

// 分配权限
const assignPermissions = async (role) => {
  currentRole.value = role
  // 加载所有权限
  await loadAllPermissions()
  // 获取角色已有权限
  const permissionIds = await getRolePermissions(role.id)
  
  // 关键优化：使用nextTick确保权限树渲染完成后再设置勾选状态
  nextTick(() => {
    checkedPermissionIds.value = permissionIds
    // 强制刷新树形组件的勾选状态
    permissionTreeRef.value?.setCheckedKeys(permissionIds)
  })
  
  // 显示对话框
  showPermissionDialog.value = true
}

// 保存权限分配
const savePermissionAssignment = async () => {
  if (!currentRole.value) return
  
  try {
    const permissionIds = permissionTreeRef.value.getCheckedKeys()
    
    const response = await assignPermissionsAPI({
      roleId: currentRole.value.id,
      permissionIds: permissionIds
    })
    
    if (response.code === 0) {
      ElMessage.success('权限分配成功')
      showPermissionDialog.value = false
    } else {
      ElMessage.error(response.data?.message || '权限分配失败')
    }
  } catch (error) {
    console.error('保存权限分配失败:', error)
    ElMessage.error('权限分配失败')
  }
}

const editRole = (role) => {
  editingRole.value = role
  roleForm.value = { ...role }
  showEditModal.value = true
}

const deleteRole = async (role) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.roleName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteSysRoleAPI(role.id)
    if (response.code === 0) {
      ElMessage.success('角色删除成功')
      loadRoles()
    } else {
      ElMessage.error(response.data?.message || '删除角色失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }
}

const saveRole = async () => {
  try {
    let response
    if (showAddModal.value) {
      // 添加新角色
      response = await addSysRoleAPI(roleForm.value)
    } else {
      // 编辑角色
      response = await updateSysRoleAPI({
        ...roleForm.value,
        id: editingRole.value.id
      })
    }
    
    if (response.code === 0) {
      ElMessage.success(showAddModal.value ? '角色添加成功' : '角色更新成功')
      closeModal()
      loadRoles()
    } else {
      ElMessage.error(response.data?.message || (showAddModal.value ? '角色添加失败' : '角色更新失败'))
    }
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error(showAddModal.value ? '角色添加失败' : '角色更新失败')
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  editingRole.value = null
  roleForm.value = {
    roleName: '',
    roleDes: '',
    status: 1
  }
}

onMounted(() => {
  // 初始化数据
  loadRoles()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 16px;
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
}
</style>